// pages/myHome/register/register.js
Page({
  data: {
    account: '',
    password: '',
    confirmPassword: ''
  },
  nameInput: function(e) {
    this.setData({
      account: e.detail.value
    });
  },
  passwordInput: function(e) {
    this.setData({
      password: e.detail.value
    });
  },
  confirmPasswordInput: function(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },
  register: function(e) {
    const account = this.data.account;
    const password = this.data.password;
    const confirmPassword = this.data.confirmPassword;
    if (account.trim() === '') {
      wx.showToast({
        title: '请输入账号',
        icon: 'none'
      });
      return;
    }
    if (password.trim() === '' || confirmPassword.trim() === '') {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }
    wx.request({
      url: 'http://localhost:8080/login/register',
      method: 'POST',
      header: {
        "content-type": "application/json;charset=UTF-8"
      },
      data: {
        username: account,
        password: password
      },
      success: function(res) {
        if (res.data.code === 200) {
          wx.showToast({
            title: '注册成功',
          });
          wx.navigateTo({
            url: '/pages/login/login',
          });
        } else if (res.data.code === 400) {
          wx.showToast({
            title: '用户已存在',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '注册失败',
            icon: 'none'
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '注册失败',
          icon: 'none'
        });
      }
    });
  }
});